package learn.web.controller;

import learn.domain.User;
import learn.domain.base.JsonModel;
import learn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by sqluogui on 2016/10/13.
 */
@Controller
public class LoginController {
    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public String login(HttpServletRequest request){
        return "login";
    }

    @RequestMapping("/jump")
    public String jump(){
        return "jump";
    }

    @RequestMapping("/checkCode")
    @ResponseBody
    public JsonModel checkCode(HttpServletRequest request,HttpSession session){
        String code = request.getParameter("code").toUpperCase();
        String realCode = session.getAttribute("code").toString();
        JsonModel jsonModel = new JsonModel();
        if(code.equals(realCode)){
            jsonModel.setCode(1);
        }else{
            jsonModel.setCode(0);
            jsonModel.setInfo("验证码错误！");
        }
        return jsonModel;
    }

    @RequestMapping("/checkUser")
    @ResponseBody
    public JsonModel checkUser(HttpServletRequest request,HttpSession session){
        String code = request.getParameter("code").toUpperCase();
        String realCode = session.getAttribute("code").toString();
        JsonModel jsonModel = new JsonModel();
        jsonModel.setCode(1);
        if(!code.equals(realCode)){
            jsonModel.setCode(0);
            jsonModel.setInfo("验证码错误！");
            return jsonModel;
        }
        String userName = request.getParameter("userName");
        String pwd = request.getParameter("password");
        User user = userService.queryByNamePwd(userName,pwd);
        if(user == null || user.getId()==0){
            jsonModel.setCode(0);
            jsonModel.setInfo("用户名或密码错误！");
            return jsonModel;
        }
        session.setAttribute("user",user);
        return jsonModel;
    }
}
